package com.ruoyi.common.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhimin.hu
 * @Date 2021/4/8
 */
@Component
public class FastJsonMessageConfig {
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {

        //1、定义一个convert转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        // 2.添加fastJson的配置信息
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
     /*   WriteMapNullValue	是否输出值为null的字段,默认为false
        WriteEnumUsingToString	Enum输出name()或者original,默认为false
        UseISO8601DateFormat	Date使用ISO8601格式输出，默认为false
        WriteNullListAsEmpty	List字段如果为null,输出为[],而非null
        WriteNullStringAsEmpty	字符类型字段如果为null,输出为”“,而非null
        WriteNullNumberAsZero	数值字段如果为null,输出为0,而非null
        WriteNullBooleanAsFalse	Boolean字段如果为null,输出为false,而非null
        PrettyFormat	结果是否格式化,默认为false
    */
        fastJsonConfig.setSerializerFeatures(
         SerializerFeature.PrettyFormat
        ,SerializerFeature.WriteMapNullValue
        ,SerializerFeature.WriteNullListAsEmpty
        ,SerializerFeature.WriteNullStringAsEmpty
        ,SerializerFeature.WriteNullNumberAsZero
        ,SerializerFeature.WriteNullBooleanAsFalse);

        //设置格式化的时间格式

        //2-1 处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_PROBLEM_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        //3、在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
        HttpMessageConverter<?> converter = fastConverter;
        return new HttpMessageConverters(converter);
    }
}
